<template>
    <div class="two-main">
        <div class="layout-content" v-if="!loading">

            <div class="aside-tow">
                <!-- 左侧操作台 -->
                <div class="aside-tow-left">
                    <div style="width: 200px;display: flex;flex-direction: column;">

                        <div style="height: 300px;">
                            <div class="step" v-if="!Myedit">Step II: Drag the events to your itinerary</div>

                            <el-menu default-active="1" class="el-menu-vertical-demo"
                                style="height: 200px;width: 200px;margin-top: 10px;">

                                <el-sub-menu index="1" class="left-menu">
                                    <template #title>
                                        <svg style="margin-right: 10px;" t="1723880559977" class="icon"
                                            viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
                                            p-id="15385" width="20" height="20">
                                            <path
                                                d="M896 448H128v447.957333l477.738667 0.021334L896 895.957333V448z m0-42.666667V192.042667C896 192 768 192 768 192V149.333333h128.042667A42.666667 42.666667 0 0 1 938.666667 192.042667v703.914666A42.624 42.624 0 0 1 896.064 938.666667H127.936A42.666667 42.666667 0 0 1 85.333333 895.957333V192.042667C85.333333 168.469333 104.256 149.333333 127.957333 149.333333H256v42.666667l-128 0.042667V405.333333h768zM298.666667 85.333333h42.666666v170.666667h-42.666666V85.333333z m384 0h42.666666v170.666667h-42.666666V85.333333zM384 149.333333h256v42.666667H384V149.333333z"
                                                fill="#2c2c2c" p-id="15386"></path>
                                        </svg>
                                        Itinerary</template>
                                    <el-scrollbar ref="scroll1" height="150px" style="margin-bottom: 10px;">
                                        <el-menu-item class="aside-menu-item" :index="index"
                                            v-for="(item, index) in plans" @click="scrollset(index)">Day
                                            {{ item.name }}
                                        </el-menu-item>
                                    </el-scrollbar>
                                </el-sub-menu>

                            </el-menu>



                            <div class="Events" v-if="!Myedit">Events added:</div>

                        </div>

                        <div style="display: flex;flex-direction: column;height: 100%;">


                            <el-scrollbar class="eventbox-scroll">
                                <div style="height: 120px;">



                                    <draggable v-if="!Myedit" group="group1" animation="1000" v-model="events"
                                        @start="EventstartDarg" @end="EventEndDarg" style="min-height: 120px;display: block;">

                                        <template #item="{ element }">
                                            <div class="event-item" draggable="true"
                                            @dragstart="EnvetdragStart($event, element, index)">
                                                <div class="event-item-content">
                                                    <img style="height: 15px;width: 15px" src="../../assets/locate.png">
                                                    <div>{{ element.name }}</div>
                                                </div>
                                            </div>
                                        </template>
                                    </draggable>

                                </div>
                            </el-scrollbar>




                            <div class="bottom-btn" v-if="!Myedit">
                                <el-button
                                    style="background-color: #ff9239;width: 160px;margin-bottom: 15px;height: 32px"
                                    type="info" @click="addEvent">Add
                                    a
                                    new event</el-button>
                                <el-button
                                    style="background-color: #ff9239;width: 160px;margin-bottom: 15px;height: 32px"
                                    type="info" @click="save">Save
                                    the
                                    plan</el-button>
                                <el-button style="background-color: #a1a1a1;width: 160px;height: 32px" type="info"
                                    @click="Discard('Discard')">Close</el-button>
                            </div>
                            <div class="bottom-btn" v-if="Myedit">
                                <el-button
                                    style="background-color: #ff9239;width: 160px;margin-bottom: 15px;height: 32px"
                                    type="danger" @click="copy">Create a
                                    copy</el-button>
                                <el-button style="background-color: #a1a1a1;width: 160px;height: 32px" type="info"
                                    @click="Discard('Close')">Close</el-button>
                            </div>

                        </div>

                    </div>
                </div>
                <!-- 左侧操作台 -->


                <!-- 左侧展示台 -->
                <div style="width: 415px; box-shadow: inset 0 0 0 1px #cccccc; ">
                    <el-scrollbar class="custom-scrollbar" ref="scrollContainer">
                        <div style="width: 415px;height: 180px;position: relative">
                            <img :src="PlanQurry.image" style="width: 414px;height: 170px;" />
                            <div class="guid-title">
                                <!-- <div v-if="item.value" class="title-name">Trip to {{ PlanQurry.region }}</div> -->
                                <div class="title-name">{{ PlanQurry.title }}</div>
                                <div style="display: flex;justify-content: space-between;align-items: flex-end;">
                                    <div class="title-time">{{ formatDateMonth(date[0]) + '-' + formatDateYear(date[1])
                                        }}
                                    </div>
                                    <img :src="data.avatar ? data.avatar : (user.avatar ? user.avatar : 'https://mdbootstrap.com/img/Photos/Avatars/img (31).jpg')"
                                        style="width: 30px;height: 30px;border-radius: 30px;" />
                                </div>
                            </div>

                        </div>

                        <div style="padding: 15px;">
                            <el-menu ref="menuRef" v-if="openeds.length > 0" :default-openeds="openeds"
                                :default-active="0">

                                <el-sub-menu class="mover" :index="index" v-for="(item, index) in plans" ref="itemRefs"
                                    style="margin-top:10px" :id="'itemRefs-' + index">
                                    <template #title>
                                        <div class="sub-menu-title" @dragover="allowDrop($event)"
                                            @drop="drop($event, index)">
                                            Day {{ item.name }} - {{ formatDateWeekday(item.date) }}
                                        </div>
                                    </template>
                   
                                    <draggable animation="1000" handle=".drag-icon" group="group1"
                                        v-model="item.content" @start="startDarg" @end="endDarg">

                                        <template #item="{ element, index2 }">

                                            <el-menu-item draggable="true"
                                                @dragstart="dragStart($event, element, index)"
                                                :class="(item.content.length > 1 && element.busIndex > 0) ? 'menu-item menu-item-top' : 'menu-item'">
                                                <div class="bus"
                                                    v-if="(item.content.length > 1 && element.busIndex > 0)">
                                                    <div style="display: flex;align-items: center;">
                                                        <img style="width: 20px;height: 20px;margin-right: 10px;"
                                                            src="@/assets/bus.png">
                                                    </div> {{ element.km && element.miu && element.km != null &&
                                                        element.miu != null ? formatDistance(element.km) + ', ' +
                                                    secondsToHMS(element.miu): "Calculating the distance" }}
                                                    <div style="display: flex;align-items: center;">
                                                        <img style="width: 15px;height: 15px;margin-left: 10px;"
                                                            src="@/assets/next.png">
                                                    </div>
                                                </div>


                                                <div v-if="!Myedit" class="drag-icon">
                                                    <div class="drag-icon-line"></div>
                                                    <div class="drag-icon-line"></div>
                                                    <div class="drag-icon-line"></div>
                                                </div>

                                                <div>
                                                    <img :src="element.image"
                                                        style="width: 120px;height: 100px;border-radius: 10px;margin-left: 10px;" />
                                                </div>
                                                <div style="display: grid;height: 100px;width: 100%;">

                                                    <div
                                                        style="display: flex;height: 30px;width: 100%;justify-content: space-between;align-items: center;">
                                                        <div
                                                            style="display: flex;height: 30px;width: 100%;align-items: center;">
                                                            <div class="locationindex">
                                                                {{ element.locationIndex }}
                                                            </div>
                                                            <div class="timeStyle">

                                                                <img src="@/assets/time.png"
                                                                    style="width: 15px;height: 15px;" />
                                                                <div class="timeStyle-timetext"
                                                                    v-if="element.time != null && element.time != ''">
                                                                    {{ element.time }}</div>
                                                            </div>
                                                        </div>
                                                        <div style="display: flex">
                                                            <div v-if="!Myedit"
                                                                style="display: flex;height: 20px;width: 100%;margin-right: 5px;"
                                                                @click="edit(index, element)">
                                                                <img src="../../assets/edit.png" alt="">

                                                            </div>
                                                            <div v-if="!Myedit"
                                                                style="display: flex;height: 20px;width: 100%;"
                                                                @click="del(index, element)">
                                                                <img src="../../assets/del.png" alt="">

                                                            </div>
                                                            <div v-if="Myedit"
                                                                style="display: flex;height: 20px;width: 100%;"
                                                                @click="look(index, element)">
                                                                <img src="../../assets/info.png" alt="">

                                                            </div>

                                                        </div>

                                                    </div>

                                                    <div
                                                        style="height: 30px;margin-left: 10px;font-size: 15px;line-height: 30px;font-weight: bold;width: 180px;
                                                         overflow:hidden;white-space: nowrap;text-overflow: ellipsis;-o-text-overflow:ellipsis;">
                                                        {{ element.name }}</div>
                                                    <div
                                                        style="bottom: 0px;margin-left: 10px;font-size: 13px;color: #858484;height: 30px;line-height: 30px;width: 180px;
                                                        overflow:hidden;white-space: nowrap;text-overflow: ellipsis;-o-text-overflow:ellipsis;">
                                                        {{ element.remark }}</div>
                                                </div>

                                            </el-menu-item>
                                        </template>
                                    </draggable>

                                </el-sub-menu>

                            </el-menu>

                        </div>
                    </el-scrollbar>
                </div>
                <!-- 左侧展示台 -->
            </div>



            <div style="display: flex;border-top: 1px solid rgb(233, 233, 233);width: 100%;">
                <scenics-detail v-if="detailDataVisible" :scenicEntity="detailData" @close="detailDataVisible = false"
                    class="scenics-detail-map"></scenics-detail>
                <div id="container" style="position: relative; height: 100%; width: 100%">

                </div>

            </div>

        </div>

        <el-dialog style="border-radius: 15px;" v-model="centerDialogVisible" title="" width="500" center
            :show-close="false">
            <form>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="Date:" prop="Date">
                            {{ formatDateYear(editDate.date) }}
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="Time:" prop="Time">
                            <!-- <el-time-picker v-model="editDate.time" placeholder="Time" /> -->
                            <el-time-select v-model="editDate.time" style="width: 240px" start="00:00" step="00:30"
                                end="23:59" placeholder="Select time" format="HH:mm" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24" style="font-size: 20px;margin-bottom: 10px;">{{ editDate.name }}</el-col>
                </el-row>
                <el-row>
                    <el-col :span="24" style="height: 100px;">
                        <el-form-item label="Remark:" prop="Date">
                            <el-input v-model="editDate.remark" type="textarea" :rows="5" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </form>
            <template #footer>
                <div class="dialog-footer" style="margin-top: 50px;">
                    <el-button class="cancel-btn" @click="centerDialogVisible = false">Cancel</el-button>
                    <el-button class="confirm-btn" @click="ConfirmEdit">
                        Confirm
                    </el-button>
                </div>
            </template>
        </el-dialog>



        <el-dialog align-center v-model="disCardDialogVisible" width="500" center :showClose="false"
            style="border-radius: 15px;" class="confirmDialog">
            <span style="display: flex;justify-content: center;font-size: large;color: #000;">{{ closeText }}</span>
            <template #footer>
                <div class="dialog-footer">
                    <el-button class="cancel-btn" @click="disCardDialogVisible = false">Cancel</el-button>
                    <el-button class="confirm-btn" type="primary" @click="confirmDisCard">
                        Confirm
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <el-dialog align-center v-model="deleteDialogVisible" width="500" center :showClose="false"
            style="border-radius: 15px;" class="confirmDialog">
            <span style="display: flex;justify-content: center;font-size: large;color: #000;">Are you sure to delete the
                travel
                event?</span>
            <template #footer>
                <div class="dialog-footer">
                    <el-button class="cancel-btn" @click="deleteDialogVisible = false">Cancel</el-button>
                    <el-button class="confirm-btn" type="primary" @click="confirmdelete">
                        Confirm
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <div class="two-main-load" v-if="loading">
            <div class="loadpage"> </div>
            <div>We're loading your page; it should just take a moment.</div>
        </div>
    </div>

</template>
<script lang="ts" setup>
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'

import { onMounted, onBeforeUnmount, onUnmounted, nextTick, computed, watch } from 'vue';
import draggable from "vuedraggable";
import Cookies from 'js-cookie';
import { useRoute, useRouter } from 'vue-router';
import { setToken, setUser, getUser } from '@/utils/auth'

import { guid, addUserguid } from '@/api/index';
import { ref } from 'vue'
import { ElScrollbar } from 'element-plus'
import { ElAmap } from "@vuemap/vue-amap";
import AMapLoader from "@amap/amap-jsapi-loader";
import scenics from '@/components/Map/scenics.vue';
import { formatDateMonth, formatDateYear, formatDateWeekday, formatDistance, secondsToHMS } from '@/utils/time';
import scenicsDetail from '@/components/Map/scenicsDetailMap.vue';
import cache from "@/plugins/cache";
import EventBus from "@/utils/event-bus"
// import Map from '@/components/Map/index.vue';
const router = useRoute();
import { useStore } from 'vuex';
const itemRefs = ref([]);
const deleteIndex = ref("");
const deleteLocateIndex = ref("");
const user = getUser();
const routers = useRouter();
const store = useStore();
const events = ref([]);
// const item = ref("");
const data = ref({});
const plans = ref([]);
const openeds = ref([]);
const doubleClickZoom = ref(true);
const PlanQurry = ref({});
const map = ref()
const trans = ref()
const date = ref([]);
const editDate = ref({});
const Myedit = ref(true);
const detailDataVisible = ref(false);
const detailData = ref({});
const disCardDialogVisible = ref(false)
const deleteDialogVisible = ref(false);
// const customScrollbarHeight = ref('')
const closeText = ref('');
// 类型定义
const scrollContainer = ref<InstanceType<typeof ElScrollbar>>();
const centerDialogVisible = ref(false)
const menuRef = ref<any>(null);
const draggedGroupIndex = ref(null)
const draggedIndex = ref(null)
const draggedElement  = ref(null)
const leftDarg = ref(false)
const control = ref({
    scale: {},
    zoom: {
        position: 'bottomRight',
    },
})
const windowHeight = ref(window.innerHeight);
// customScrollbarHeight.value = windowHeight.value - 88
store.commit('setGuidEdit'); // 通过 dispatch 触发 mutation
const riskSpreadRefList = ref([]);
const getRiskSpreadRef = (el, index) => {
    if (el) {
        riskSpreadRefList.value[index] = el;
    }
};
// const updateButtonVisibility = () => {
//     customScrollbarHeight.value = windowHeight.value - 185
// };
function Discard(item) {
    if (item == "Discard") {
        closeText.value = "Are you sure to discard the plan created?"
        disCardDialogVisible.value = true;
    } else {
        // closeText.value = "Are you sure to Close the plan?"
        routers.push({
            path: cache.session.getJSON("prePath")
        })
    }

}
function confirmDisCard() {
    routers.push({
        path: cache.session.getJSON("prePath")
    })
}
const loading = ref(true)
// 从路由的查询参数中获取 id
const item = computed(() => router.query.id || '');
//  const itemId = computed(() => route.query.id || 'default-id');
function init() {

    store.commit('setGuidEdit'); // 通过 dispatch 触发 mutation
    window._AMapSecurityConfig = {
        securityJsCode: "1484eb7c8bfff81f249064649b5a1d74"
    }

    if (router.query.id) {
        item.value = router.query.id

        getGuid();

        if (cache.session.getJSON('events')) {
            if (cache.session.getJSON('events').length > 0) {
                events.value = cache.session.getJSON('events')

            }
        }
    } else {
        loading.value = false
        Myedit.value = false;
        if (cache.session.getJSON('events')) {
            if (cache.session.getJSON('events').length > 0) {
                events.value = cache.session.getJSON('events')

            }
        }

        if (cache.session.getJSON('plans')) {
            plans.value = cache.session.getJSON('plans');
            PlanQurry.value = JSON.parse(Cookies.get('setPlanQurry'))
            const Dates = getDatesBetween(PlanQurry.value.date[0], PlanQurry.value.date[1])
            date.value = PlanQurry.value.date
            for (let index = 0; index < plans.value.length; index++) {
                openeds.value.push(index)
            }
        }
        else {
            PlanQurry.value = JSON.parse(Cookies.get('setPlanQurry'))
            const Dates = getDatesBetween(PlanQurry.value.date[0], PlanQurry.value.date[1])
            date.value = PlanQurry.value.date
            for (let index = 0; index < Dates.length; index++) {
                let date = Dates[index];
                let obj = {
                    content: [],
                    date: date,
                    name: index + 1,
                    title: "第" + (index + 1) + "天"
                }
                plans.value.push(obj)
                openeds.value.push(index)
            }
        }
    }


    // if (router.query.date) {
    mapload()
    // 获取 Cookie
}
// 监听 id 的变化
watch(() => router.query.id, (newId) => {
    init();
});
//... ...
onMounted(async () => {
    await nextTick();
    // window.addEventListener('resize', updateButtonVisibility);
    init();



    // }
})
// 在组件卸载时移除 ResizeObserver 监听
onUnmounted(() => {
    // window.removeEventListener('resize', updateButtonVisibility);
    store.commit('setFalseGuidEdit');
});
onBeforeUnmount(() => {
    map.value?.destroy();

    // 进行必要的清理操作，比如移除事件监听器
});

function edit(index, params) {

    editDate.value = {
        id: params.id,
        time: params.time,
        remark: params.remark
    }
    editDate.value.date = plans.value[index].date
    editDate.value.index = index;
    editDate.value.locationIndex = params.locationIndex;
    centerDialogVisible.value = true
}
function look(index, params) {

    detailData.value = params
    detailDataVisible.value = true
}
function ConfirmEdit() {
    const element = plans.value[editDate.value.index].content
    if (plans.value[editDate.value.index].content.length > 0) {
        plans.value[editDate.value.index].content.forEach(e => {
            if (e.locationIndex === editDate.value.locationIndex) {
                e.time = editDate.value.time
                e.remark = editDate.value.remark
            }
        });

    }
    cache.session.setJSON('plans', plans.value);
    centerDialogVisible.value = false
}
function confirmdelete() {
    const element = plans.value[deleteIndex.value].content
    console.log(element)
    let deleteId = 0;
    for (let index = 0; index < element.length; index++) {
        const e = element[index];
        if (e.locationIndex === deleteLocateIndex.value) {
            deleteId = index;
            console.log(deleteId)
        }
    }
    element.splice(deleteId, 1)
    plans.value[deleteIndex.value].content = element;
    deleteDialogVisible.value = false;
    mapload()
    getlocationindex();
    setMarkers();
}
function del(index, params) {
    deleteDialogVisible.value = true;
    deleteIndex.value = index;
    deleteLocateIndex.value = params.locationIndex;
    console.log(deleteIndex.value, deleteLocateIndex.value)
}



function setTitle() {

    for (let index = 0; index < plans.value.length; index++) {
        const element = plans.value[index];
        for (let i = 0; i < element.content.length; i++) {
            const el = element.content[i];

            if (i == 0) {

                el['titlename'] = "DAY " + element.name + "-" + formatDateWeekday(element.date)
            }
            if (i > 0) {
                el['titlename'] = "Depart from " + element.content[i - 1].name
                el['bustime'] = element.content[i - 1].endTime + " - " + element.content[i].startTime
            }
        }
    }
}





//拖拽结束的事件
const onEnd = () => {
    console.log("结束拖拽");
    setTitle();

};
function getlocationindex() {
    let locationIndex = 1;
    for (let index = 0; index < plans.value.length; index++) {
        const element = plans.value[index];
        const places = element.content.length;
        if (places > 0) {
            for (let j = 0; j < element.content.length; j++) {
                const contentitem = element.content[j];
                contentitem.locationIndex = locationIndex;
                contentitem.busIndex = j
                locationIndex++;
            }
        }
    }
}
async function savePlans() {
    // Cookies.set(plans.value.id+'-plans',JSON.stringify(plans.value))
    let places = 0;
    let image = ""
    for (let index = 0; index < plans.value.length; index++) {
        const element = plans.value[index];
        places = places + element.content.length
        if (element.content.length > 0) {

            image = element.content[0].image

        }
    }

    if (!places > 0) {
        ElMessage({
            type: 'error',
            message: 'Please add Events',
        })
        return;
    }
    let data = {
        title: PlanQurry.value.title,
        region: PlanQurry.value.region,
        days: plans.value.length,
        nights: plans.value.length - 1,
        places: places,
        image: PlanQurry.value.image,
        startTime: PlanQurry.value.date[0],
        endTime: PlanQurry.value.date[1],
    }
    if (item.value) {
        data.id = item.value;
    }
    data.plans = plans.value
    addUserguid(data).then(res => {
        if (res.code == 500) {
            ElMessage({
                type: 'error',
                message: 'error',
            })
            return;
        }
        ElMessage({
            type: 'success',
            message: 'Your changes have been saved',
        })
        cache.session.remove('events')
        routers.push({
            path: '/profileinfo'
        })
    })
}


const count = ref(0)
const value = ref(3.7)


const load = () => {
    count.value += 2
}
function start(e) {
}
function setBus(e) {
    getlocationindex();
    setMarkers();
    if (plans.value && plans.value.length > 0) {
        // 遍历计划
        for (let index = 0; index < plans.value.length; index++) {
            const element = plans.value[index];
            if (element.content.length > 1) {
                for (let j = 0; j < element.content.length - 1; j++) {

                    let scenic = element.content[j];
                    let nextscenic = element.content[j + 1];
                    // 异步查询公交换乘路线
                    trans.value.search([scenic.longitude, scenic.latitude], [nextscenic.longitude, nextscenic.latitude], function (status, result) {
                        if (status === 'complete') {
                            element.content[j + 1].km = result.plans ? result.plans[0].distance : 0
                            element.content[j + 1].miu = result.plans ? result.plans[0].time : 0
                        } else {
                        }
                    });
                }
            }
        }
    }
}

function mapload() {
    AMapLoader.load({
        key: "db17a89f9c977760ebb6a8ca01e092b8", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0" // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15

        // plugins: [], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    }).then((AMap) => {
        let center = [116.397428, 39.90923];
        if (null != plans.value && plans.value.length > 0 && null != plans.value[0].content) {
            let first = plans.value[0].content[0]
            if (null != first && null != first.longitude) {
                center = [first.longitude, first.latitude]
            }
        }

        const policy = 'LEAST_TIME';


        // 确保地图 API 加载完成后执行
        AMap.plugin('AMap.Transfer', function () {
            let transOptions = {
                city: "香港", // 公交城市
                policy: AMap.TransferPolicy.LEAST_TIME // 乘车策略
            };
            trans.value = new AMap.Transfer(transOptions);

        });

        setBus();



        map.value = new AMap.Map("container", {
            // 设置地图容器id
            // viewMode: "3D", // 是否为3D地图模式
            zoom: 11, // 初始化地图级别
            center: center, // 初始化地图中心点位置
            autoFitView: true,
        });


        setMarkers()


    })
        .catch((e) => {
        });
}

function setMarkers() {
    if (null != plans.value && plans.value.length > 0 && map.value) {
        let x = 0;
        let markers = [];
        let center = [];
        for (let index = 0; index < plans.value.length; index++) {
            const element = plans.value[index].content;
            for (let j = 0; j < element.length; j++) {
                x = x + 1;
                const planitem = element[j];
                let markerContent = '' +
                    '<div style=" position: relative;">' +
                    '   <img style=" width: 25px;height: 34px;" src="//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png">' +
                    '   <div style="position: absolute;top: 5px;right: 1px;width: 15px;height: 15px;font-size: 12px;color:#fff">' + x + '</div>' +
                    '</div>';
                if (planitem.longitude && planitem.latitude) {
                    let position = new AMap.LngLat(planitem.longitude, planitem.latitude); //Marker 经纬度
                    let center = [planitem.longitude, planitem.latitude];
                    let marker = new AMap.Marker({
                        position: position,
                        content: markerContent, //将 html 传给 content
                        offset: new AMap.Pixel(-13, -30), //以 icon 的 [center bottom] 为原点
                    });
                    markers.push(marker)
                }
            }
        }

        // map.value = new AMap.Map("container", {
        // // 设置地图容器id
        // // viewMode: "3D", // 是否为3D地图模式
        // zoom: 11, // 初始化地图级别
        // center: center, // 初始化地图中心点位置
        // });
        map.value.add(markers);
        map.value.setFitView();
    }
}
function getGuid() {
    guid({ id: item.value }).then(res => {
        if (null != user && user.email != res.data.attribute) {
            Myedit.value = true;
        }
        if (null != user && user.email == res.data.attribute) {
            Myedit.value = false;
        }
        data.value = res.data
        PlanQurry.value['region'] = res.data.region
        PlanQurry.value['title'] = item.value ? res.data.title : "Trip to " + res.data.region;
        PlanQurry.value['date'] = [res.data.startTime, res.data.endTime]
        PlanQurry.value['image'] = res.data.image
        plans.value = res.data.plans
        date.value = [res.data.startTime, res.data.endTime]
        for (let index = 0; index < plans.value.length; index++) {
            openeds.value.push(index)
        }

        if (cache.session.getJSON('plans') != null) {

            plans.value = cache.session.getJSON('plans');
            console.log("cache.session.getJSON('plans')", cache.session.getJSON('plans'))
        }
        // setTitle()
        mapload()
        getlocationindex()
        loading.value = false
    })
}


function formatDate(string) {
    const date = new Date(string);
    const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

    const day = date.getDate();
    const month = months[date.getMonth()];
    const weekday = days[date.getDay()];

    return `${day} ${month} ${weekday}`;
}


async function scrollset(index) {

    menuRef.value.open(index)
    await nextTick();

    ScrollTop(index)




}

// 将目标元素滚动到顶部
function ScrollTop(index) {
    const box = document.getElementById('itemRefs-' + index)
    const top = box?.offsetTop;
    console.log('itemRefs-' + index, top)
    // let top = 10;
    // for (let j = 0; j < index; j++) {
    //     const item = itemRefs.value[j].$el;
    //     console.log("item.clientHeight",item.clientHeight)
    //     top = top + item.clientHeight;
    // }
    // console.log(170 + top + index * 60)

    scrollContainer.value?.setScrollTop(top + 200);
}



function save() {
    savePlans();
}
function copy() {
    detailDataVisible.value = false
    if (!user) {
        EventBus.emit("p-click", '父传子文本信息');
        return;
    }

    let places = 0;
    for (let index = 0; index < plans.value.length; index++) {
        const element = plans.value[index];
        places = places + element.content.length
    }
    if (!plans.value[0].content[0]) {
        ElMessage({
            type: 'error',
            message: 'Please add Events',
        })
        return;
    }
    cache.session.remove('events')
    let data = {
        title: PlanQurry.value.title,
        region: PlanQurry.value.region,
        days: plans.value.length,
        nights: plans.value.length - 1,
        places: places,
        image: PlanQurry.value.image,
        startTime: PlanQurry.value.date[0],
        endTime: PlanQurry.value.date[1],
    }
    data.plans = plans.value
    addUserguid(data).then(res => {
        if (res.code == 500) {
            ElMessage({
                type: 'error',
                message: 'error',
            })
            return;
        }
        ElMessage({
            type: 'success',
            message: 'Your copy has been created',
        })
        cache.session.remove('plans')

        routers.push({
            path: '/stepTwo',
            query: { id: res.data.id }
        })
        if (user.email != res.data.attribute) {
            Myedit.value = true;
        }
        // location.reload()
    })
}

function addEvent() {
    // Cookies.set("plans", JSON.stringify(plans.value))
    // sessionStorage.removeItem('plans');
    cache.session.setJSON('events', events.value);
    cache.session.setJSON('plans', plans.value);
    Cookies.set("setPlanQurry", JSON.stringify(PlanQurry.value))
    if (item.value) {
        routers.push({
            path: '/stepOne',
            query: {
                id: item.value
            }
        })
    } else {
        routers.push({
            path: '/stepOne'
        })
    }

}


function calculateDaysBetweenDates(startDateStr, endDateStr) {
    // 将日期字符串解析为 Date 对象
    const startDate = new Date(startDateStr);
    const endDate = new Date(endDateStr);

    // 计算两个日期之间的差值（以毫秒为单位）
    const diffInMillis = endDate - startDate;

    // 将毫秒转换为天数
    const diffInDays = Math.ceil(diffInMillis / (1000 * 60 * 60 * 24));

    return diffInDays;
}


function getDatesBetween(startDateStr, endDateStr) {
    // 将日期字符串解析为 Date 对象
    const startDate = new Date(startDateStr);
    const endDate = new Date(endDateStr);

    // 结果数组
    const dates = [];

    // 当前日期从起始日期开始
    let currentDate = new Date(startDate);

    // 循环直到当前日期超过结束日期
    while (currentDate <= endDate) {
        // 将当前日期格式化为字符串并添加到结果数组
        dates.push(new Date(currentDate).toISOString().split('T')[0]);

        // 将当前日期增加一天
        currentDate.setDate(currentDate.getDate() + 1);
    }

    return dates;
}
function EventstartDarg(params:type) {
    leftDarg.value = true
}
function EventEndDarg(params:type) {
    setBus()
}
//拖拽开始的事件
function startDarg(params: type) {
    console.log("开始拖拽");
    leftDarg.value = false
}
function endDarg(params:type) {
    setBus()
    leftDarg.value = false
}
const eventDaraElement = ref(null)
function EnvetdragStart(event, element, index) {
    eventDaraElement.value = element
}
function dragStart(event, element, index) {
    draggedElement.value = element;
    draggedGroupIndex.value = index;
}
function allowDrop(event) {
    event.preventDefault();
}
function drop(event, targetIndex) {
    event.preventDefault();

    if(!leftDarg.value){
        console.log("移入目标group", targetIndex)
    console.log("移出源group", draggedGroupIndex.value)
    if (targetIndex != draggedGroupIndex.value) {
        const sourceIndex = plans.value[draggedGroupIndex.value].content.indexOf(draggedElement.value);
        if (sourceIndex !== -1) {
            plans.value[draggedGroupIndex.value].content.splice(sourceIndex, 1);
            plans.value[targetIndex].content.push(draggedElement.value);
        }
        console.log(plans.value[targetIndex])
        
        setBus()
    }
    }else{
        console.log("移入目标group", targetIndex)
        console.log("移出源:Events", draggedGroupIndex.value)
        const eventssourceIndex = events.value.indexOf(eventDaraElement.value);
        if (eventssourceIndex !== -1) {
            events.value.splice(eventssourceIndex, 1);
            plans.value[targetIndex].content.push(eventDaraElement.value);
        }
    }

    
}
</script>
<style>
.two-main {
    display: flex;
    /* 使用Flexbox布局 */
    flex-direction: column;
    /* 子元素垂直排列 */
    height: calc(100vh - 88px);
    /* 高度为视口高度减去头部高度 */
}

.two-main-load {
    display: flex;
    height: calc(100vh - 88px);
    justify-content: center;
    align-items: center;
    flex-direction: column;
    color: #5a5a5a;
}

.layout-content {
    display: flex;
    /* flex: 1; */
    min-height: 100%;
    /* 高度至少为主容器的高度 */
}

/* 确认框 start*/
.cancel-btn {
    background-color: #cacaca;
    border-color: #c9c9c9;
    margin-right: 65px;
    color: #000;
    width: 100px;
}

.cancel-btn:hover {
    background-color: #9a9a9a;
    border-color: #9a9a9a;
    color: #000;
}

.cancel-btn:active {
    background-color: #9a9a9a;
    border-color: #9a9a9a;
    color: #000;
}

.confirm-btn {
    background-color: #ff8800;
    border-color: #ff8800;
    color: #000;
    width: 100px;
}

.confirm-btn:hover {
    background-color: #ffa33a;
    border-color: #ffa33a;
    color: #000;
}

.confirm-btn:active {
    background-color: #ffa33a;
    border-color: #ffa33a;
    color: #000;
}

/* 确认框 end*/
.scenics-detail-map {
    position: absolute;
    height: 335px;
    max-width: 600px;
    width: 100%;
    z-index: 99;
    background: #fff;
    border-radius: 15px;
    bottom: 46px;
    margin-left: 10px;
}

.guid-title {
    position: absolute;
    bottom: 0;
    left: 35px;
    right: 35px;
    height: 110px;
    background: rgb(255, 255, 255);
    color: rgb(0, 0, 0);
    padding: 15px;
    border-radius: 25px 25px 0px 0px;

}

.title-name {
    font-weight: bolder;
    font-size: 25px;
    text-overflow: ellipsis;
    /* ellipsis:显示省略符号来代表被修剪的文本  string:使用给定的字符串来代表被修剪的文本*/
    white-space: nowrap;
    /* nowrap:规定段落中的文本不进行换行   */
    overflow: hidden;
    /*超出部分隐藏**/
}

.title-time {
    margin-top: 15px;
    font-size: 15px;
}

.el-menu {
    background-color: var(--el-menu-bg-color);
    border-right: 0px solid var(--el-menu-border-color);
    box-sizing: border-box;
    list-style: none;
    margin: 0;
    padding-left: 0;
    position: relative;

}



.aside-tow {
    display: flex;
    border-top: 1px solid rgb(233, 233, 233);
    border-right: 1px solid rgb(233, 233, 233);
}

.step {
    font-weight: bold;
    color: black;
    width: 200px;
}

.Events {
    font-size: 14px;
    color: #757575;
    margin-top: 15px;
}

.event-item {
    width: 200px;
    display: flex;
    font-size: 13px;
    color: #000;
    background-color: #f1f1f1;
    padding: 5px;
    padding-left: 10px;
    line-height: 25px;
    margin-top: 5px;
    border-radius: 5px;
    cursor: pointer;

}

.event-item-content {
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
}

.bottom-btn {
    /* position: absolute; */
    margin-top: 15px;
    margin-bottom: 15px;
    display: grid;
    place-items: center;
    width: 200px;
    /* height: 126px; */
    /* background-color: #fff; */
    /* 背景颜色可以自定义 */
    /* padding: 10px; */
    /* display: flex; */
    /* flex-flow: column nowrap; */
    /* flex-wrap: wrap; */
    /* align-items: center;
    width: inherit; */
}


.el-sub-menu__title {
    height: 40px;
    line-height: 40px;
    background-color: #f3f3f3;
    border-radius: 10px;
    margin-bottom: 10px;
}

.el-sub-menu .aside-menu-item {
    height: 30px;
    background-color: #f3f3f3;
    margin-bottom: 10px;
    border-radius: 10px;
    width: 95%;
}

.el-sub-menu .main-menu-item {
    height: 120px;
    background-color: #f3f3f3;
    margin-bottom: 5px;
    border-radius: 10px;
    display: grid;
    justify-content: start;
    width: 95%;
    padding-left: 10px;
}

.el-sub-menu .menu-item {
    background-color: #f3f3f3;
    width: 372px;
    height: 120px;
    /* margin-bottom: 10px; */
    border-radius: 10px;
}

.menu-item-top {

    margin-top: 50px;

}

.el-sub-menu .el-menu {
    margin-top: 5px;
    border-left: 2px solid #dddddd;
    display: grid;
    /* justify-items: end; */
    padding-left: 10px;
    /* height: 150px; */
}

.left-menu {
    height: 150px;
}

.el-menu--vertical:not(.el-menu--collapse):not(.el-menu--popup-container) .el-menu-item,
.el-menu--vertical:not(.el-menu--collapse):not(.el-menu--popup-container) .el-menu-item-group__title,
.el-menu--vertical:not(.el-menu--collapse):not(.el-menu--popup-container) .el-sub-menu__title {
    padding-left: 10px;
}

.bus {
    height: 50px;
    position: absolute;
    top: -50px;
    width: 100%;
    display: flex;
    justify-content: center;
    /* border-left: 2px solid #cecece; */
}

.bus::before {
    content: '';
    position: absolute;
    top: 3px;
    left: 0%;
    /* 从中间开始显示 */
    width: 1px;
    /* 边框的宽度 */
    height: 44px;
    /* 边框的高度 */
    background-color: #cecece;
    /* 边框的颜色 */
    transform: translateX(-50%);
    /* 使边框居中 */
}

.messageBoxP_confirmBtn {
    background-color: #ff9b3d;
    border-color: #ff9239;

}

.messageBoxP_confirmBtn>.el-button {
    margin-right: 100px;
}

.el-message-box {
    height: 150px;
    border-radius: 20px;
}

.el-message-box__btns {
    display: flex;
    padding-top: var(--el-messagebox-padding-primary);
    flex-wrap: wrap;
    margin-top: 20px;
}

.el-message-box__message p {
    line-height: var(--el-messagebox-font-line-height);
    margin: 0;
    font-size: 17px;
    margin-top: 10px;
}

.el-button+.el-button {
    margin-left: 0;
}

.aside-tow-left {
    width: 250px;
    background-color: #fff;
    overflow-y: hidden;
    overflow-x: hidden;
    border-top: 1px solid #ebebeb;
    display: flex;
    justify-content: center;
    padding-top: 10px;
}

.custom-scrollbar {
    width: 100%;
    height: 100%;
}

.el-textarea__inner {
    resize: none;
}

.locationindex {
    width: 25px;
    height: 25px;
    color: #fff;
    background-color: #ee3838;
    line-height: 15px;
    align-items: center;
    display: flex;
    justify-content: center;
    border-radius: 15px;
    margin-left: 10px;
}

.timeStyle {
    border-radius: 20px;
    background-color: rgb(224 224 224);
    max-width: 70px;
    height: 25px;
    display: flex;
    padding: 5px;
    margin-left: 10px;
    justify-content: space-evenly;
}

.timeStyle>p {
    width: 29.8px;
}

.drag-icon {
    display: flex;
    width: 26px;
    justify-content: space-between;
    cursor: move;
}

.drag-icon-line {
    width: 3px;
    background-color: #7d7d7d;
    height: 20px;
}

.eventsDrag {


    background-color: #cccccc;
    position: relative;
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    height: 100%;
    min-height: 120px;
    max-height: fit-content;


    align-content: flex-start;
    justify-content: center;
    align-items: center;

}

.eventbox-scroll {
    height: 100%;
    min-height: 120px;
}

.eventbox {

    overflow-y: auto;
    overflow-x: hidden;
    height: 100%;
    min-height: 120px;
    background-color: #7d7d7d;
}

.noneEventText {
    width: 100%;
    position: absolute;
    font-size: 12px;
    background-color: #fafafa;
    height: 120px;
    display: flex;
    place-content: center;
    align-items: center;

}

.timeStyle-timetext {
    font-size: 12px;
    max-width: 32px;
    height: 15px;
    display: flex;
    align-items: center;
    overflow: hidden;
    margin-left: 5px;
}

.loadpage {
    position: relative;
    width: 60px;
    height: 60px;
    border: 5px solid #ff8827;
    border-top-color: rgba(255, 134, 34, 0.2);
    border-right-color: rgba(255, 117, 37, 0.2);
    border-bottom-color: rgba(255, 118, 39, 0.2);
    border-radius: 100%;

    animation: circle infinite 0.75s linear;
}

@keyframes circle {
    0% {
        transform: rotate(0);
    }

    100% {
        transform: rotate(360deg);
    }
}

.chosenClass {
    height: 372px;
}

.ghost {}
</style>